﻿using System.Collections.Generic;
using System.Linq;
using Internal.KuiHuaBaoDian.Services.UI.Toggle;
using KuiHuaBaoDian.Services.UGUI.Layout;
using UnityEngine;
using UnityEngine.Assertions;
using UnityEngine.UI;

namespace KuiHuaBaoDian.Services.UGUI.Toggle {

    /// <summary>
    /// 开关组服务
    /// </summary>
    public static class ToggleService {

        /// <summary>
        /// 单例
        /// </summary>
        public static IToggleService Instance => m_Instance ??= KHBD.TypeMap.Instantiate<IToggleService>();
        private static IToggleService m_Instance;
    }

    /// <summary>
    /// 开关组服务
    /// </summary>
    public interface IToggleService {

        /// <summary>
        /// 注册一个开关组
        /// </summary>
        /// <param name="layoutGroup">开关的布局组</param>
        /// <param name="elementPrefab">开关元素预制体</param>
        /// <param name="datas">元素数据</param>
        /// <returns>开关组服务句柄</returns>
        ToggleHandle<TData> Register<TData>(LayoutGroup layoutGroup, IToggleElement elementPrefab, IEnumerable<ToggleData<TData>> datas);

        /// <summary>
        /// 注销一个开关组
        /// </summary>
        /// <param name="handle">需要注销的已注册过的开关服务句柄</param>
        void Unregister(ToggleHandle handle);
    }

    [Implement(typeof(IToggleService))]
    internal sealed class KHBD_ToggleService : IToggleService, IService {

        void IService.OnApplicationQuit() { }

        public ToggleHandle<TData> Register<TData>(LayoutGroup layoutGroup, IToggleElement elementPrefab, IEnumerable<ToggleData<TData>> datas) {
            Assert.IsNotNull(layoutGroup);
            Assert.IsNotNull(elementPrefab);
            Assert.IsNotNull(datas);

            var layoutHandle = LayoutService.Instance.Register<ToggleData<TData>, LayoutHandle<ToggleData<TData>>>(layoutGroup, elementPrefab, (uint)datas.Count());
            var handle = new ToggleHandle<TData>();
            (handle as IToggleHandleInternal).LayoutHandle = layoutHandle;
            foreach (var data in datas) {
                if (data == null) {
                    Debug.LogError($"[{nameof(ToggleService)}.{nameof(Register)}()] 参数 {nameof(datas)} 中包含了空值，跳过");
                    continue;
                }
                LayoutService.Instance.AddElement(layoutHandle, data);
            }
            return handle;
        }

        public void Unregister(ToggleHandle handle) {
            Assert.IsNotNull(handle);

            var layoutHandle = (handle as IToggleHandleInternal).LayoutHandle;
            LayoutService.Instance.Unregister(layoutHandle);
        }
    }
}
